package org.apache.ibatis.io;

import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>ResolverUtil is used to locate classes that are available in the/a class path and meet
 * arbitrary conditions. The two most common conditions are that a class implements/extends
 * another class, or that is it annotated with a specific annotation. However, through the use
 * of the {@link Test} class it is possible to search using arbitrary conditions.</p>
 *
 * <p>A ClassLoader is used to locate all locations (directories and jar files) in the class
 * path that contain classes within certain packages, and then to load those classes and
 * check them. By default the ClassLoader returned by
 * {@code Thread.currentThread().getContextClassLoader()} is used, but this can be overridden
 * by calling {@link #setClassLoader(ClassLoader)} prior to invoking any of the {@code find()}
 * methods.</p>
 *
 * <p>General searches are initiated by calling the
 * {@link #find(org.apache.ibatis.io.ResolverUtil.Test, String)} ()} method and supplying
 * a package name and a Test instance. This will cause the named package <b>and all sub-packages</b>
 * to be scanned for classes that meet the test. There are also utility methods for the common
 * use cases of scanning multiple packages for extensions of particular classes, or classes
 * annotated with a specific annotation.</p>
 *
 * <p>The standard usage pattern for the ResolverUtil class is as follows:</p>
 *
 * <pre>
 * ResolverUtil&lt;ActionBean&gt; resolver = new ResolverUtil&lt;ActionBean&gt;();
 * resolver.findImplementation(ActionBean.class, pkg1, pkg2);
 * resolver.find(new CustomTest(), pkg1);
 * resolver.find(new CustomTest(), pkg2);
 * Collection&lt;ActionBean&gt; beans = resolver.getClasses();
 * </pre>
 *
 * @author Tim Fennell
 * @worshiper MNIQXH
 * @param <T>
 *          the generic type
 */
public class ResolverUtil<T> {

    /**
     * An instance of Log to use for logging in this class.
     */
    public static final Log log = LogFactory.getLog(ResolverUtil.class);

    /**
     * A simple interface that specifies how to test classes to determine if they
     * are to be included in the results produced by the ResolverUtil.
     * 一个简单的接口用来指定如何测试类，以确定它们是否包好在ResolverUtil生成的结果中。
     */
    public interface Test {
        /**
         * Will be called repeatedly with candidate classes. Must return True if a class
         * is to be included in the results, false otherwise.
         * 重复调用候选类，如果一个类包含在其中则必返回true，否则返回false
         *
         * @param type the type
         * @return true, if successful
         */
        boolean matches(Class<?> type);
    }

    /**
     * A test that checks to see if each class is assignable to the provided class. Note
     * that this test will match the parent type itself if it is presented for matching.
     */
    public static class IsA implements Test {
        /**
         * The parent.
         */
        private Class<?> parent;

        /**
         * Constructs an IsA test using the supplied Class as the parent class/interface.
         *
         * @param parentType the parent type
         */
        public IsA(Class<?> parentType) {
            this.parent = parentType;
        }

        /** Returns true if type is assignable to the parent type supplied in the constructor. */
        @Override
        public boolean matches(Class<?> type) {
            return type != null && parent.isAssignableFrom(type);
        }

        @Override
        public String toString() {
            return "is assignable to " + parent.getSimpleName();
        }
    }

    /**
     * A Test that checks to see if each class is annotation with a specific annotation. If it
     * is, then the test returns true, otherwise false.
     */
    public static class AnnotationWith implements Test {

        /**
         * The annotation
         */
        private Class<? extends Annotation> annotation;

        /**
         * Constructs an Annotation test for the specified annotation type.
         *
         * @param annotation the annotation
         */
        public AnnotationWith(Class<? extends Annotation> annotation) {
            this.annotation = annotation;
        }

        /** Returns true if the type is annotation with the class provided to the constructor. */
        @Override
        public boolean matches(Class<?> type) {
            return type != null && type.isAnnotationPresent(annotation);
        }

        @Override
        public String toString() {
            return "annotation with @" + annotation.getSimpleName();
        }
    }

    /** The set of matches being accumulated. */
    private Set<Class<? extends T>> matches = new HashSet<>();

    /**
     * The ClassLoader to use when looking for classes. If null then the ClassLoader returned
     * by Thread.currentThread().getContextClassLoader() will be used.
     * 该类加载器被用来查找类，如果返回值是null会使用Thread.currentThread().getContextClassLoader()。
     */
    private ClassLoader classLoader;

    /**
     * Provides access to the classes discovered so far. If no class have been made to
     * any of the {@code find()} methods, this set will be empty.
     * 提供已发现类的访问，如果没有类使用{@code find()}被创建,该集合可能是空。
     *
     * @return the set of classes that have bean discovered.
     */
    public Set<Class<? extends T>> getClasses() {
        return matches;
    }

    /**
     * Returns the classloader that will be used for scanning for classes. If no explicit
     * ClassLoader has been set by the calling, the context class loader will be used.
     * 返回将用于扫面类的类加载器。如果没有设置显示的类加载器，将使用上下文的类加载器。
     *
     * @return the ClassLoader that will be used to scan for classes
     */
    public ClassLoader getClassLoader() {
        return classLoader == null ? Thread.currentThread().getContextClassLoader() : classLoader;
    }

    /**
     * Sets an explicit ClassLoader that should be used when scanning for classes. If none
     * is set then the context classloader will be used.
     * 设置用来扫描类的显示类加载器，如果设置为空则使用上下文的类加载器。
     *
     * @param classLoader a ClassLoader to use when scanning for classes
     */
    public void setClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }


    /**
     * Attempts to discover classes that are assignable to the type provided. In the case
     * that an interface is provided this method will collect implementations. In the case
     * of a non-interface class, subclasses will be collected. Accumulated classes can be
     * accessed by calling {@link #getClasses()}.
     * 尝试发现可归于指定类型的类。是接口的情况它的实现类会被该方法收集。是非接口类的情况子类会被收集。
     * 累计的类可以通过调用{@link #getClasses()}获取。
     *
     * @param parent       the classes of interface to find subclasses or implementations of
     * @param packageNames one or more package names to scan (including subpackage) for classes
     * @return the resolver util
     */
    public ResolverUtil<T> findImplementations(Class<?> parent, String... packageNames) {
        if (packageNames == null) {
            return this;
        }

        Test test = new IsA(parent);
        for (String pkg : packageNames) {
            find(test, pkg);
        }

        return this;
    }

    /**
     * Attempts to discover classes that are annotated with the annotated. Accumulated
     * classes can be accessed by calling {@link #getClasses()}.
     * 尝试发现被指定注解注解的类。累计的类可以通过调用{@link #getClasses()}获取。
     *
     * @param annotation   the annotation that should be present on matching classes
     * @param packageNames one or more package names to scan (including subpackage) for classes
     * @return the resolver util
     */
    public ResolverUtil<T> findAnnotated(Class<? extends Annotation> annotation, String... packageNames) {
        if (packageNames == null) {
            return this;
        }

        Test test = new AnnotationWith(annotation);
        for (String pkg : packageNames) {
            find(test, pkg);
        }

        return this;
    }

    /**
     * Scans for classes staring at the package provided and descending into subpackages.
     * Each class is offered up to the Test as it is discovered, and if the Test returns
     * true the class is retained.  Accumulated classes can be fetched by calling {@link #getClasses()}.
     * 从提供的包和子包扫描类。
     * 每一个被发现的类会被提供给Test，如果Test返回true则保留该类。累计的类可以通过{@link #getClasses()}调用获取。
     *
     * @param test        an instance of {@link Test} that will be used to filter classes
     * @param packageName the name of the package from which to start scanning for classes,
     *                    e.g. {@code net.sourceforge.stripes}
     * @return the resolver util
     */
    public ResolverUtil<T> find(Test test, String packageName) {
        String path = getPackagePath(packageName);
        try {
            List<String> children = VFS.getInstance().list(path);
            for (String child : children) {
                if (child.endsWith(".class")) {
                    addIfMatching(test, child);
                }
            }
        } catch (IOException ioe) {
            log.error("Could not read package: " + packageName, ioe);
        }
        return this;
    }

    /**
     * Converts a Java package name to a path that can be looked up with a call to
     * {@link ClassLoader#getResources(String)}
     * 将一个Java包名转换成一个能被{@link ClassLoader#getResources(String)}调用的地址。
     *
     * @param packageName The Java package name to convert to path
     * @return the package path
     */
    protected String getPackagePath(String packageName) {
        return packageName == null ? null : packageName.replace('.', '/');
    }

    /**
     * Add the class designated by the fully qualified class name provided to the set of
     * resolved classes if and only if it is approved by the Test supplied.
     * 当且仅当Test类批准，将指定的类的完全限定名添加到已解析的类集合。
     *
     * @param test the test used to determine if the class matches
     * @param fqn  the fully qualified name of a class
     */
    protected void addIfMatching(Test test, String fqn) {
        try {
            String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
            ClassLoader loader = getClassLoader();
            if (log.isDebugEnabled()) {
                log.debug("Checking to see if class " + externalName + " matches criteria [" + test + "]");
            }

            Class<?> type = loader.loadClass(externalName);
            if (test.matches(type)) {
                matches.add((Class<T>) type);
            }
        } catch (Throwable t) {
            log.warn("Could not examine class '" + fqn + "'" + " due to a "
                    + t.getClass().getName() + " with message: " + t.getMessage());
        }
    }

}
